<template>
  <div style="padding: 10px">
    <div style="display: flex; justify-content: space-between">
      <el-space>
        <el-button style="margin-bottom: 20px" :icon="Plus" type="primary" @click="openAddDialog">
          添加 Augment 账号
        </el-button>
        <el-button style="margin-bottom: 20px" :icon="Plus" type="info" @click="addBatch">
          批量添加 Augment 账号
        </el-button>
      </el-space>
      <el-space>
        <el-input
          v-model="pageParams.email"
          placeholder="请输入邮箱"
          clearable
          @clear="handleClear"
          @keydown.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" :icon="Search">搜索</el-button>
          </template>
        </el-input>
      </el-space>
    </div>

    <el-table v-loading="loading" :data="tableData" style="width: 100%" border stripe>
      <el-table-column type="index" label="序号" width="70" align="center" />
      <el-table-column prop="email" label="邮箱">
        <template #default="{ row }">
          <div style="display: flex; align-items: center">
            <span>{{ row.email }}</span>
            <CopyButton :text="row.email" success-message="邮箱复制成功" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="账号类型" width="100" prop="account_type" align="center">
        <template #default="{ row }">
          <el-tag v-if="!row.account_type" disable-transitions type="info">未知</el-tag>
          <el-tag v-if="row.account_type === '50'" disable-transitions type="warning">50</el-tag>
          <el-tag v-if="row.account_type === '125'" disable-transitions type="info">125</el-tag>
          <el-tag v-if="row.account_type === '650'" disable-transitions type="success">650</el-tag>
          <el-tag v-if="row.account_type === '725'" disable-transitions type="danger" effect="dark">725</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" width="150" label="创建时间" align="center">
        <template #default="{ row }">
          <el-text type="success">{{ getCreateDaysText(row.create_time) }}</el-text>
        </template>
      </el-table-column>
      <el-table-column label="是否过期" width="150" prop="manual_expiration" align="center">
        <template #default="{ row }">
          <el-tag disable-transitions hit v-if="row.manual_expiration === 0" type="info">
            未过期
          </el-tag>
          <el-tag disable-transitions hit v-if="row.manual_expiration === 1" type="danger">
            已过期
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220px" align="center" fixed="right">
        <template #default="{ row }">
          <el-button plain :icon="Edit" type="warning" @click="openEditDialog(row)">编辑</el-button>
          <el-button plain :icon="Delete" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 20px; display: flex; justify-content: center">
      <el-pagination
        background
        v-model:currentPage="pageParams.pageNum"
        v-model:page-size="pageParams.pageSize"
        :total="total"
        :pager-count="7"
        @current-change="currentChange"
        @size-change="sizeChange"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </div>

  <el-dialog v-model="dialogParam.visible" :title="dialogParam.title" width="650px">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="邮 箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="账号类型" prop="account_type">
        <el-select v-model="form.account_type" value-key="value" placeholder="请选择账号类型">
          <el-option
            v-for="item in selectOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否过期" prop="manual_expiration">
        <el-switch
          v-model="form.manual_expiration"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: flex-end">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="submitForm">
          {{ dialogParam.type === "edit" ? "更新" : "添加" }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    title="批量添加 Augment 账号"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    v-model="batchDialogShow"
    width="650px"
    :before-close="beforeClose"
  >
    <el-input
      v-model="batchAccount"
      type="textarea"
      :autosize="{ minRows: 20, maxRows: 25 }"
      placeholder="请粘贴批量数据"
      clearable
    />
    <template #footer>
      <div style="display: flex; justify-content: flex-end">
        <el-button @click="handleBatchCancel">取消</el-button>
        <el-button type="primary" @click="handleBatchConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { markRaw, ref, onMounted } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { Plus, Delete, Edit, Search } from "@element-plus/icons-vue"
import {
  getAccountListAPI,
  addAccountAPI,
  deleteAccountAPI,
  updateAccountAPI,
  getAccountAugmentEmailListAPI
} from "@/api/augment"
import CopyButton from "@/components/CopyButton.vue"
import dayjs from "dayjs"

const tableData = ref([])
const loading = ref(false)
const dialogParam = ref({
  visible: false,
  type: "add",
  title: "添加账户"
})
const currentData = ref({})
const formRef = ref(null)
const form = ref({
  _id: "",
  email: "",
  manual_expiration: 0,
  account_type: "50"
})
const rules = markRaw({
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
  ]
})
const selectOptions = ref([
  { id: 1, label: "50", value: "50" },
  { id: 2, label: "125", value: "125" },
  { id: 3, label: "650", value: "650" },
  { id: 4, label: "725", value: "725" }
])
const total = ref(0)
const pageParams = ref({
  pageNum: 1,
  pageSize: 10,
  email: ""
})
const batchDialogShow = ref(false)
const batchAccount = ref("")

onMounted(() => {
  getDataList()
})

const getDataList = async () => {
  loading.value = true

  const res = await getAccountListAPI(pageParams.value)
  if (res.errCode === 0) {
    total.value = res.count
    tableData.value = res.data
    loading.value = false
  }
}

const currentChange = current => {
  pageParams.value.pageNum = current
  getDataList()
}
const sizeChange = size => {
  pageParams.value.pageNum = 1
  pageParams.value.pageSize = size
  getDataList()
}

// 重置表单
const resetForm = () => {
  form.value._id = ""
  form.value.email = ""
  form.value.manual_expiration = 0
  form.value.account_type = "125"
  currentData.value = {}
  formRef.value?.clearValidate()
}

// 添加
const openAddDialog = () => {
  resetForm()
  dialogParam.value = {
    visible: true,
    type: "add",
    title: "添加账户"
  }
}
const addBatch = () => {
  batchAccount.value = ""
  batchDialogShow.value = true
}
const handleBatchCancel = () => {
  batchAccount.value = ""
  batchDialogShow.value = false
}
const handleBatchConfirm = async () => {
  if (!batchAccount.value) {
    ElMessage.error("请先粘贴数据")
    return
  }

  let emails = []
  const data = []
  const res = await getAccountAugmentEmailListAPI()
  if (res.errCode === 0 && Array.isArray(res.data)) {
    emails = res.data.map(i => i.email)
  }

  try {
    const accounts = JSON.parse(batchAccount.value)
    if (!Array.isArray(accounts)) {
      ElMessage.error("数据格式错误，请确保是JSON数组格式")
      return
    }

    for (const ele of accounts) {
      if (!ele || !ele.email) {
        continue // 跳过无效数据
      }

      // 检查数据库中是否已存在该邮箱
      if (emails.includes(ele.email)) {
        console.log(`邮箱 ${ele.email} 已存在，跳过`)
        continue
      }

      // 检查当前批次中是否有重复
      if (data.some(item => item.email === ele.email)) {
        console.log(`邮箱 ${ele.email} 在当前批次中重复，跳过`)
        continue
      }

      data.push({
        email: ele.email,
        manual_expiration: 0,
        account_type: "50"
      })
    }

    if (data.length === 0) {
      ElMessage.warning("没有找到可导入的有效数据")
      return
    }

    console.log(`准备导入 ${data.length} 个账号:`, data)

    // 批量添加账号
    let successCount = 0
    let failCount = 0

    for (const account of data) {
      try {
        const addRes = await addAccountAPI(account)
        if (addRes.errCode === 0) {
          successCount++
        } else {
          failCount++
          console.error(`添加账号 ${account.email} 失败:`, addRes.errMsg)
        }
      } catch (error) {
        failCount++
        console.error(`添加账号 ${account.email} 出错:`, error)
      }
    }

    // 显示结果
    if (successCount > 0) {
      ElMessage.success(
        `成功导入 ${successCount} 个账号${failCount > 0 ? `，失败 ${failCount} 个` : ""}`
      )
      getDataList() // 刷新列表
    } else {
      ElMessage.error(`导入失败，共 ${failCount} 个账号导入失败`)
    }

    batchDialogShow.value = false
    batchAccount.value = ""
  } catch (error) {
    console.error("JSON解析错误:", error)
    ElMessage.error("数据格式错误，请检查JSON格式是否正确")
  }
}
const handleSearch = () => {
  getDataList()
}
const handleClear = () => {
  pageParams.value.email = ""
  getDataList()
}

// 修改
const openEditDialog = row => {
  resetForm()
  currentData.value = { ...row }
  Object.assign(form.value, row)
  dialogParam.value = {
    visible: true,
    type: "edit",
    title: "编辑账户"
  }
}

// 提交添加和修改
const submitForm = async () => {
  formRef.value?.validate(async valid => {
    if (valid) {
      if (dialogParam.value.type === "edit") {
        const res = await updateAccountAPI(form.value)
        if (res.errCode === 0) {
          ElMessage.success("修改成功")
          getDataList()
          dialogParam.value.visible = false
        }
      } else {
        const res = await addAccountAPI(form.value)
        console.log(res)
        if (res.errCode === 0) {
          ElMessage.success("添加成功")
          getDataList()
          dialogParam.value.visible = false
        }
      }
    }
  })
}

// 确认删除
const handleDelete = row => {
  ElMessageBox.confirm(`确定要删除邮箱为 ${row.email} 的账户吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const res = await deleteAccountAPI(row)
      if (res.errCode === 0) {
        ElMessage.success("删除成功")
        getDataList() // 刷新列表
      }
    })
    .catch(() => {
      console.log("取消删除")
    })
}

// 计算创建天数文本
const getCreateDaysText = createTimestamp => {
  if (!createTimestamp) return "未知"
  return dayjs(createTimestamp).format("YYYY-MM-DD HH:mm")
}

const handleCancel = async () => {
  dialogParam.value.visible = false
}
</script>

<style lang="scss" scoped></style>
